package com.shapawan.tourism.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shapawan.tourism.entity.SysIcon;
import com.shapawan.tourism.mapper.SysIconMapper;
import com.shapawan.tourism.service.SysIconService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 系统图标Service实现类
 */
@Service
@Slf4j
public class SysIconServiceImpl extends ServiceImpl<SysIconMapper, SysIcon> implements SysIconService {

    @Override
    public SysIcon getByCode(String code) {
        LambdaQueryWrapper<SysIcon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysIcon::getCode, code);
        return getOne(queryWrapper);
    }

    @Override
    public boolean updateWithContent(SysIcon icon, String fileContent) {
        // 更新图标内容
        if (fileContent != null && !fileContent.isEmpty()) {
            // 处理Base64编码内容，移除可能的前缀
            if (fileContent.contains(",")) {
                fileContent = fileContent.substring(fileContent.indexOf(",") + 1);
            }
            icon.setContent(fileContent);

            // 根据文件内容判断图标类型
            if (fileContent.startsWith("<svg")) {
                icon.setType("svg");
            } else if (!fileContent.isEmpty() && icon.getType() != null && "font".equals(icon.getType())) {
                // 字体图标，直接保存内容
                icon.setContent(fileContent);
            } else {
                icon.setType("image");
            }
        }

        // 更新状态，默认启用
        if (icon.getStatus() == null) {
            icon.setStatus(1);
        }

        // 如果是新增，检查编码是否存在
        if (icon.getId() == null && icon.getCode() != null) {
            SysIcon existIcon = getByCode(icon.getCode());
            if (existIcon != null) {
                log.error("图标编码已存在: {}", icon.getCode());
                return false;
            }
        }

        return saveOrUpdate(icon);
    }

    @Override
    public boolean updateStatus(Integer id, Integer status) {
        SysIcon icon = getById(id);
        if (icon == null) {
            return false;
        }

        icon.setStatus(status);
        return updateById(icon);
    }
} 